package model;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;

/**
 * This class is able to generate a matrix of characters, randomly distributed.
 * It also assures a minimal number of vocals (must reasonably be minor or equal
 * than rows*columns)
 * 
 * @author simone
 *
 */
public class RandomCharMatrixCreator {

	private static final char[] VOCALS = { 'a', 'e', 'i', 'o', 'u' };
	private char[][] matrix;
	private int rows;
	private int columns;
	private int vocalsNumber;

	/**
	 * Creates a new istance of this class, by specifying the salient parameters
	 * of the desired matrix
	 * 
	 * @param rows
	 *            : the number of rows of that matrix
	 * @param columns
	 *            : the number of columns of that matrix
	 * 
	 * @param vocalsNumber
	 *            : the minimal number of vocals to be in that matrix. To
	 *            properly work, vocalsNumber should be minor or equal than
	 *            rows*columns
	 */
	public RandomCharMatrixCreator(int rows, int columns, int vocalsNumber) {
		super();
		this.rows = rows;
		this.columns = columns;
		this.vocalsNumber = vocalsNumber;
	}

	/**
	 * Performs the creation
	 * 
	 * @return: the desired matrix of characters
	 */
	public char[][] createMatrix() {
		matrix = new char[rows][columns];
		ArrayList<Character> list = fillList();
		Collections.shuffle(list);
		listToMatrix(list);
		return matrix;
	}

	private ArrayList<Character> fillList() {
		ArrayList<Character> list = new ArrayList<Character>();
		Random randomGenerator = new Random();
		putVocals(list, randomGenerator);
		putCharacters(list, randomGenerator);
		return list;
	}

	private void putCharacters(ArrayList<Character> list, Random randomGenerator) {
		for (int i = 0; i < rows * columns - vocalsNumber; i++) {
			list.add((char) (97 + randomGenerator.nextInt(25)));
		}
	}

	private void putVocals(ArrayList<Character> list, Random randomGenerator) {
		for (int i = 0; i < vocalsNumber; i++) {
			list.add(VOCALS[randomGenerator.nextInt(VOCALS.length)]);
		}
	}

	private void listToMatrix(ArrayList<Character> list) {
		int k = 0;
		for (int i = 0; i < matrix.length; i++) {
			for (int j = 0; j < matrix[i].length; j++) {
				matrix[i][j] = list.get(k);
				k++;
			}
		}
	}

}
